
package juc.mythread.create;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

import static java.lang.Thread.*;

/**
 * @ClassName TestVirtualPlatform
 * @PackageName mythread.create
 * @projectName myThread
 * @Description 测试平台线程与虚拟线程
 * @Author games
 * @Date 2025/8/25 下午4:27
 * @Version 1.0
 */
/*
 * 如果您确实使用的是Java 21+，请确保：
 * 检查项目JDK设置是否正确指向Java 21
 * 在编译和运行时添加预览特性参数：
 * 编辑器 --enable-preview
 * 项目模块 --enable-preview
 * maven --enable-preview
 * 配置vm --enable-preview
 *  javac --enable-preview --source 21 TestVirtualPlatform.java
 *  java --enable-preview TestVirtualPlatform
 *
 * */
public class TestVirtualPlatform {
    public static void main(String[] args) throws InterruptedException {

        // 启动一个平台线程
        Thread.ofPlatform().start(() -> System.out.println("Platform Thread: " + currentThread()));

        // 启动一个虚拟线程
        Thread vt = Thread.ofVirtual().start(() -> System.out.println("Virtual Thread: " + currentThread()));
        vt.join();

        // 使用虚拟线程执行大量任务，观察线程数量
        Set<String> threadNames = ConcurrentHashMap.newKeySet();
        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
            IntStream.range(0, 100000).forEach(i -> {
                executor.submit(() -> {
                    String threadInfo = Thread.currentThread().toString();
                    /* Executing task 99808: 正在执行第99808号任务
                     * VirtualThread[#99881]: 这是一个虚拟线程，ID为99881
                     * runnable@ForkJoinPool-1-worker-15: 该虚拟线程当前运行在ForkJoinPool-1的第15号工作线程上*/
                    //Executing task 99808 on thread VirtualThread[#99881]/runnable@ForkJoinPool-1-worker-15
                    System.out.println("Executing task " + i + " on thread " + threadInfo);
                    String[] parts = threadInfo.split("/");
                    if (parts.length > 1) {
                        System.out.println("Virtual Thread: " + parts[1]);
                        threadNames.add(parts[1]);
                    }
                    return i;
                });
            });

            Thread.sleep(5000);
            System.out.println("Unique Virtual Threads (approx): " + threadNames.size());
        }
    }
}
